<template>
  <!-- 页脚 -->
  <footer class="border-t mt-16">
    <div class="container py-8 text-center text-sm text-muted-foreground">
      © {{ new Date().getFullYear() }} 橘子. All rights reserved.
    </div>
  </footer>

  <!-- 滑动到顶部按钮 -->
  <button
    @click="scrollToTop"
    style="box-shadow: 1px 1px 8px 3px hsl(var(--border));"
    class="fixed bottom-16 right-6 p-2 rounded-full bg-background transition-all duration-300 opacity-0 filter"
    :class="{
      'opacity-100': showBackToTop,
      'opacity-0': !showBackToTop,
      'cursor-pointer': showBackToTop,
      'cursor-default': !showBackToTop,
    }"
    aria-label="回到顶部"
  >
    <!-- 进度条 -->
    <svg class="absolute inset-0 h-full w-full" viewBox="0 0 100 100">
      <circle
        class="progress-ring__circle stroke-primary stroke-[8px] fill-transparent"
        r="46"
        cx="50"
        cy="50"
        transform="rotate(-90 50 50)"
        :style="progressStyle"
      />
    </svg>
    <!-- 图标 -->
    <ChevronUp class="h-8 w-8 relative text-primary" />
  </button>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ChevronUp } from 'lucide-vue-next'

// 响应式变量
const showBackToTop = ref(false)
const scrollProgress = ref(0) // 滚动进度（0 到 1）

// 计算进度条的样式
const progressStyle = computed(() => {
  const circumference = 2 * Math.PI * 46 // 圆的周长
  const offset = circumference * (1 - scrollProgress.value)
  return {
    strokeDasharray: `${circumference} ${circumference}`,
    strokeDashoffset: offset,
  }
})

// 监听滚动事件
const handleScroll = () => {
  const scrollY = window.scrollY // 获取当前页面的垂直滚动距离
  const totalHeight = document.documentElement.scrollHeight - window.innerHeight // 计算页面的总滚动高度（文档总高度 - 视口高度）
  scrollProgress.value = scrollY / totalHeight // 计算当前滚动进度
  showBackToTop.value = scrollY > 100 && scrollProgress.value !== 0
}

// 平滑滚动到顶部
const scrollToTop = () => {
  if (!showBackToTop.value) return

  // 使用原生平滑滚动
  window.scrollTo({
    top: 0,
    behavior: 'smooth', // 平滑滚动
  })

  // 监听滚动事件，更新进度条
  const onScroll = () => {
    const scrollY = window.scrollY
    const totalHeight = document.documentElement.scrollHeight - window.innerHeight
    scrollProgress.value = scrollY / totalHeight

    // 如果滚动到顶部，隐藏按钮并移除监听器
    if (scrollY === 0) {
      showBackToTop.value = false
      window.removeEventListener('scroll', onScroll)
    }
  }

  // 添加滚动事件监听器
  window.addEventListener('scroll', onScroll)
}

// 挂载和卸载滚动监听
onMounted(() => {
  window.addEventListener('scroll', handleScroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<style scoped>
/* 进度条样式 */
.progress-ring__circle {
  transition: stroke-dashoffset 0.1s linear;
}
</style>